package com.pvdnc.riru.system_server;

import android.content.ComponentName;
import android.util.Log;

import com.pvdnc.riru.system_server.filter.PackageFilterManager;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import andhook.lib.xposed.XC_MethodHook;
import andhook.lib.xposed.XposedBridge;

public class HookDevicePolicyService {

    private static final String TAG=HookDevicePolicyService.class.getSimpleName();

    private ClassLoader mCL;

    public Class<?> loadClass(String name) throws Exception {
        return mCL.loadClass(name);
    }

    public HookDevicePolicyService(ClassLoader cl){
        mCL=cl;
    }

    public void hookAll(){
        try {
            hookGetActiveAdmins();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void hookGetActiveAdmins() throws Exception {
        Class<?> dpmsClass=loadClass("com.android.server.devicepolicy.DevicePolicyManagerService");
        //public List<ComponentName> getActiveAdmins(int userHandle)
        Method method= dpmsClass.getDeclaredMethod("getActiveAdmins",
                int.class);
        XposedBridge.hookMethod(method,new XC_MethodHook(){
            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                try{
                    Object result=param.getResult();
                    if(result==null){
                        Log.w(TAG,"it seems that no dpm component registered");
                        return;
                    }
                    List<ComponentName> adminList= (List<ComponentName>) result;
                    //筛选特定的DeviceAdmin
                    Iterator<ComponentName> itor=adminList.iterator();
                    while (itor.hasNext()){
                        ComponentName cn=itor.next();
                        String pkgName=cn.getPackageName();
                        if(!HookPackageManagerService.REMOVE_ALL_DEVICE_ADMIN
                        && PackageFilterManager.INSTANCE.callFilter(pkgName))
                            continue;
                        Log.d(TAG,"attempt to remove dpm admin:"+cn);
                        itor.remove();
                    }
                    //更新
                    Log.d(TAG,"finish patching active admins list");
                    param.setResult(adminList);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        Log.d(TAG,"finish hooking getActiveAdmins");
    }
}
